package simData;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
*
* Bachelor thesis at the Institute of Biomedical Engineering, 
* located at the UMIT/EWZ campus in Hall in Tyrol. <br><br>
*
* This class is responsible for writing the results of a simulation to files.
* 
* @author Stefan Fuchs
*
*/
public class SimData {

	private String actiovationTimeFileName;
	
	private String potentialFileName;
	
	
	private static SimData INSTANCE = null;
	
	public static synchronized SimData getInstance() {
		
		if ( INSTANCE == null) {
			INSTANCE = new SimData();
		}
		
		return INSTANCE;
		
	}
	
	/**
	 * Constructor to create the essential files
	 */
	private SimData() {
		String imagetitle = ij.WindowManager.getCurrentImage().getTitle();
		SimpleDateFormat dateFormat =  new SimpleDateFormat("HH_mm_ss - dd.MM.yyyy");
		Date date = new Date(System.currentTimeMillis());
		
		this.actiovationTimeFileName = imagetitle +"_activation_time_" + dateFormat.format(date) + ".csv";
		this.potentialFileName = imagetitle + "_potentials_" + dateFormat.format(date) + ".csv";
		
		createFileHeader(this.actiovationTimeFileName, "Cellindex;A(t)\n");
		createFileHeader(this.potentialFileName, "Cellindex;t(ms);Phi(t)\n");
	}
	
	/**
	 * Creates the File Header
	 * 
	 * @param file
	 * 		The filename
	 * @param date
	 * 		The Creation Timestamp
	 */
	private void createFileHeader(String file, String columnTitle) {
		
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(file));
			bw.write(columnTitle);
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Write the activationtime for each cell
	 * 
	 * @param cellIndex
	 * 			The Index of the cell
	 * @param activationTime
	 * 			The activationtime (in milliseconds ms)
	 */
	public void writeActivationTime(long cellIndex, long activationTime) {
		
		String row = cellIndex + ";" + activationTime + "\n";  
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(this.actiovationTimeFileName,true));
			bw.write(row);
			bw.flush();
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Writes the data for each timestep of a cell
	 * 
	 * @param cellIndex
	 * 			The Index of the cell
	 * @param time
	 * 			The timestamp (int milliseconds ms)
	 * @param potential
	 * 			The Potential (in millivolts mV) 
	 */
	public void writePotentialAtTime(long cellIndex, long time, int potential) {
		
		String row = cellIndex + ";" + time + ";" + potential + "\n";  
		
		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(this.potentialFileName,true));
			bw.write(row);
			bw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}